// pages/home/home.js
const comm = require('../../utils/common.js');
const manager = require('../../utils/favManager.js');
const noti = require('../../utils/WxNotificationCenter.js');
const util = require('../../utils/util.js');
const utilService = require('../../utils/utilService.js');
const httpUtils = require('../../utils/httpUtils.js');
const wxSocket = require("../../utils/wxSocket").wxSocket;
const wsUtil = require('../../utils/wsUtils.js');

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showService: 0,
    isLoading: true,
    scene: "default",
    screenHeight: comm.screenHeight,
    screenWidth: comm.screenWidth,
    is_modal_Hidden: true,
    is_modal_Msg: '封装的一个提示框',
    showTopBar: false,
    showBackTop: false,//是否显示回到顶部
    title: "更有2018个限量红包等你来拿",
    windowDisplay: "none",
    index: 0,//分类列表选中索引
    userSweets: 0,
    usedGoods: 0,
    shareMsg: {},//分享信息
    codes_count: 0,
    //商品列表数据源
    dataSource: [],
    //分类列表数据源
    hotList: [
      {
        id: '0',
        title: '发现'
      }, {
        id: '1',
        title: '时尚'
      }, {
        id: '2',
        title: '美妆'
      }, {
        id: '3',
        title: '母婴'
      }, {
        id: '4',
        title: '书籍'
      }, {
        id: '5',
        title: '居家'
      }, {
        id: '6',
        title: '数码'
      }, {
        id: '-1',
        title: '其他'
      }
    ],
    //分页
    hasNextPage: false,
    startPage: 0,  //开始页
    productType: 0,//商品列表类型
    loadMoreData: '果冻正在努力奔跑，请耐心等待',
    // 侧滑栏
    open: false,
    lastSelected: 0,
    array: [{
      title: '默认排序',
      isSelected: false,
    }, {
      title: '按发布时间',
      isSelected: false,
    }, {
      title: '按收藏热度',
      isSelected: false,
    }, {
      title: '按果冻数从高到低',
      isSelected: false,
    }, {
      title: '按果冻数从低到高',
      isSelected: false,
    }],
    sendOverChecked: false,
    sendingChecked: false,
    allNewChecked: false,
    sameCityChecked: false,
  },

  didTapBanner(res) {
    if (res.detail == "" || res.detail == null) {
      return
    }
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      // url: "/pages/common/paySuccess/paySuccess",
      url: '../../' + res.detail,
    })
  },
  /**
   * 提交formid
   */
  submitForm: function (e) {
    // 获取表单id
    let formId = e.detail.formId;
    getApp().saveUserFormId(formId, 19);
  },
  //点击赚花
  zhuanhuaClick: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/mineSubs/pages/getFlowers/getFlowers',
    })

  },
  //点击去拿商品
  goByClick: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/home/pages/products/products',
    })
  },

  //点击开心果冻
  guodongClick: function (e) {
    this.setData({
      codes_count: 0,
      showService: 1
    })
    wx.switchTab({
      url: '/pages/happyJelly/jellyHome/jellyHome',
    })
  },

  /**
   * 点击现金红包
   *     // "getCash": "/utils/component/getCash/getCash"
         // "sweetsAnimation":"/utils/component/sweetsAnimation/sweetsAnimation"
   */
  cashClick: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/redPacket/pages/openGroup/openGroup'
    })
  },

  //点击抢兑
  qiangduiClick: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/redPacket/pages/hotExchange/hotExchange',
    })

  },
  //点击闪拍
  shanpaiClick: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/redPacket/pages/groupBuy/groupBuy',
    })
  },
  //点击logo图
  logoClick:function(e){
    this.setData({
      showService: 1
    })

    wx.switchTab({
      url: '/pages/happyJelly/jellyHome/jellyHome',
    })
  },
  //点击果冻王
  guodongwangClick: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/redPacket/pages/rankings/rankings',
    })
  },

  /**
   * 点击友物
   */
  friendProductsClick: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/home/pages/products/products?type=-5',
    })
  },

  //点击签到
  qiandaoClick: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({

      url: '/redPacket/pages/signIn/signIn'
    })
  },

  //点击邀请有礼
  inviteClick: function (e) {


  },

  // 点击侧滑栏
  slideClick: function (e) {
    this.setData({
      open: true
    })
  },

  // 点击已送出
  sendOver: function (e) {
    this.setData({
      sendOverChecked: true,
      sendingChecked: false
    })
  },

  // 点击赠送出
  sending: function (e) {
    this.setData({
      sendOverChecked: false,
      sendingChecked: true
    })
  },

  // 点击全新
  allNew: function (e) {
    this.setData({
      allNewChecked: !this.data.allNewChecked
    })
  },

  // 点击同城
  sameCity: function (e) {
    this.setData({
      sameCityChecked: !this.data.sameCityChecked
    })
  },


  // 宝贝属性分类
  onItemClick: function (e) {
    let idx = e.currentTarget.dataset.idx;
    this.data.array[this.data.lastSelected].isSelected = false;
    this.data.array[idx].isSelected = true;
    this.setData({
      array: this.data.array,
      lastSelected: idx
    })
  },

  // 重置
  reset: function (e) {
    let length = this.data.array;
    this.data.array[this.data.lastSelected].isSelected = false;
    this.setData({
      array: this.data.array,
      sendOverChecked: false,
      sendingChecked: false,
      allNewChecked: false,
      sameCityChecked: false,
      lastSelected: 0,
    })
  },
  // 完成
  complete: function (e) {
    this.setData({
      open: false,
      startPage: 0
    })
    this.getData(false);
  },

  // 关闭侧滑
  closeSlide: function (e) {
    this.setData({
      open: false
    })
  },
  //搜索事件
  search: function (e) {
    this.goSearch(e)
  },
  //分类点击
  classListItemDidSelect: function (e) {
    this.setData({
      index: e.currentTarget.dataset.idx,
      productType: e.currentTarget.dataset.id,
      dataSource: [],
      startPage: 0
    });
   var that = this
    this.getData(false, function(data) {
      // if (that.data.showTopBar == false) {
      // wx.pageScrollTo({
      //   scrollTop: that.data.screenHeight * 0.901,
      //   duration: 200
      // });
      // }

    })
  },
  goSearch: function (e) {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/home/pages/searchList/searchList',
    })
  },
  /**
   * view触底监听
   */
  onReachBottom: function () {
    var self = this;
    // 当前页是最后一页
    if (!self.data.hasNextPage) {
      self.setData({
        loadMoreData: '暂无更多数据'
      })
      return;
    }
    setTimeout(function () {
      self.setData({
        hideBottom: false
      })
      self.setData({
        startPage: self.data.startPage + 1
      })
      self.getData(true);
    }, 300);
  },
  // 获取数据  pageIndex：页码参数
  getData: function (addMore, callback) {
    if (typeof addMore == "function") {
      callback = addMore
    }
    var self = this;
    let param = new Object();
    param['startPage'] = this.data.startPage;
    param['type'] = this.data.productType;
    if (this.data.lastSelected != 0) {
      param['sort'] = this.data.lastSelected - 1;
    }
    if (this.data.sendOverChecked) {
      param['property'] = 0;
    } else if (this.data.sendingChecked) {
      param['property'] = 1;
    }
    if (this.data.allNewChecked && !this.data.sameCityChecked) {
      param['choose'] = 0;
    } else if (!this.data.allNewChecked && this.data.sameCityChecked) {
      param['choose'] = 1;
    } else if (this.data.allNewChecked && this.data.sameCityChecked) {
      param['choose'] = -1;
    }
    utilService.requestProducts(param, function (data) {
      var newData = [];
      if (addMore) {
        newData = self.data.dataSource.concat(data.items);
      } else {
        newData = data.items;
      }
      self.setData({
        dataSource: newData,
        hasNextPage: data.hasNextPage,
        isLoading: false,
      })
      typeof callback == "function" && callback(data)
    });
  },

  close: function (e) {
    this.setData({
      windowDisplay: "none",
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // options 中的 scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    var scene = decodeURIComponent(options.scene)
    this.setData({
      scene: scene
    })
    var self = this;
    //通知 - 当有别的页面 有做过 收藏 删除收藏等动作 执行通知
    this.needRefreshProducts = false
    noti.addNotification(noti.refreshProdutsNotiName, self.refreshProductds, self)
    self.codeAlert = self.selectComponent("#codeAlert");
    //授权
    self.authAlert = self.selectComponent("#authAlert");
    self.authAlert.bindCatch()
    app.loginPromise.then(() => {
      wx.showTabBar()
      self.setData({
        showService:1
      })
      self.loadData();
      self.cashCheck();
      self.connect();
      // 请求底部消息显示数量
      app.utilService.requestMessage();
    });
  },
  connect: function () {
    wsUtil.connect(function (res) {
    }, function (err) {
    })
  },
  onReceive: function (message) {
    if (message.type == "get_period_code") {
      console.log('获得密码：' + message)
      this.codeAlert.show(message.codes_count)
      this.setData({
        codes_count: message.codes_count
      })
    }
  },
  authSuccess() {
    wx.showTabBar()
    this.setData({
      showService: 1
    })
    console.log("授权 信息", app.globalData.userInfo)
    this.loadData()
    // 请求底部消息显示数量
    app.utilService.requestMessage();
    self.connect()
  },
  cashCheck() {
    var getCash = this.selectComponent("#getCash");
    getCash.check()
  },

  loadData: function () {
    let that = this;
    var scene = this.data.scene;
    if (scene != "undefined" && scene != null) {
      utilService.inserUserChannel(scene);
    }
    //可能认识的人
    this.possibleFriends = this.selectComponent("#possibleFriends");
    this.possibleFriends.ready(function () {
      // that.queryMultipleNodes();
    })

    this.advertising = this.selectComponent("#advertising");
    this.advertising.prepare()

    this.awardAlert = this.selectComponent("#awardAlert");
    this.awardAlert.ready()

    this.getData(false);
    //轮播图
    this.banner = this.selectComponent("#banner");
    this.banner.loadData(1);
    this.getUserMessage();
    this.getShareMessage(1)
  },

  getUserMessage: function () {
    var self = this;
    //获取用户能够买的宝贝数量
    app.func.Get(false, app.api.goods_can_buy_count, { 'userId': app.globalData.userId }, function (res) {
      app.globalData.usedGoods = res
      self.setData({
        usedGoods: res
      })
    })
    //获取用户多少个果冻
    app.func.Get(true, app.api.get_userInfo, { 'userId': app.globalData.userId }, function (data) {
      app.globalData.userSweets = data.integral
      self.setData({
        userSweets: app.globalData.userSweets
      })
    });
  },
  //获取分享信息
  getShareMessage: function (type) {
    var self = this;
    utilService.shareSettings(type,
      function (data) {
        self.setData({
          shareMsg: data
        })
      },
      function (error) {

      }
    );
  },
  // 通知 刷新商品
  refreshProductds: function () {
    this.needRefreshProducts = true
  },

  //他们发布的商品
  possibleFriendsCheck: function () {
    this.setData({
      showService: 1
    })
    wx.navigateTo({
      url: '/home/pages/products/products?type=-5',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
    this.setData({
      userSweets: app.globalData.userSweets
    })
    wx.showShareMenu({
      withShareTicket: true,
      success: function (res) {
        // 分享成功
      },
      fail: function (res) {
        // 分享失败
      }
    })
    if (this.needRefreshProducts == true) {
      this.needRefreshProducts = false
      this.setData({ dataSource: this.data.dataSource })
    }
    if (app.globalData.token) {
      this.cashCheck()
      // 请求未读消息总数量
      app.utilService.requestMessage();
    }
    wx.showTabBar({
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this
    noti.removeNotification(noti.refreshProdutsNotiName, that)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

    this.getUserMessage();
    this.banner.loadData(1);
    this.possibleFriends.ready();
    this.setData({
      startPage: 0
    });
    this.getData(false, function (e) {
      wx.stopPullDownRefresh()
    });
  },
  /**
   * alert点击取消回调
   */
  cancelCallBack: function () {
  },

  /**
   * alert点击确定回调
   */
  confirmCallBack: function (e) {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: this.data.shareMsg.title,
      path: "pages/home/home?userId=" + app.globalData.userId,
      imageUrl: this.data.shareMsg.pic,
      shareInfo: app.globalData.userInfo,
      success: function (res) {
        wx.showToast({
          title: "转发成功",
          icon: 'success',
          duration: 2000
        })
      },

      fail: function (res) {
        // 转发失败
        console.info("转发失败")
      }
    }
  },

  /**
   * 回到顶部
   */
  backTop: function (e) {
    wx.pageScrollTo({
      scrollTop: 0
    });
  },
  
    /**
   * 监听页面滚动e
   */
  onPageScroll: function (e) { // 获取滚动条当前位置
    var actionView = this.selectComponent("#actionView")
    if (e.scrollTop > 1500) {
      var that = this
      actionView.showBack(function () {
        that.backTop()
      })
    } else {
      actionView.dismissBack()
    }
    if (e.scrollTop / this.data.screenHeight >= 0.9) {
      // 避免时刻都在刷新，加一个判断
      if (!this.data.showTopBar) {
        this.setData({
          showTopBar: true
        })
      }
    } else {
      if (this.data.showTopBar) {
        this.setData({
          showTopBar: false
        })
      }
    }
  },

  queryMultipleNodes: function () {
    let that = this;
    // var rpx = 147;
    // var systemInfo = wx.getSystemInfoSync();
    // var px = rpx / 750 * systemInfo.windowHeight;
    var query = wx.createSelectorQuery()
    query.select('#tab').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      if (res == undefined) {
        return
      }
      that.setData({
        tabTop: res[0].top < 200 ? 314 : res[0].top// #the-id节点的上边界坐标
      })
    })
  }

})